package com.mgq.netty.c9;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.AdaptiveRecvByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author MaGuangQi
 * @description: 粘包的第一种解决办法,此方法只能解决粘包,无法解决半包
 * 由上面我们可以知道,粘包要么是发送端发的过多,或者接收端窗口过大(收取的内容多)导致的
 * 那么我们简单的方法就是,每次发送内容,发送完断开连接,再发送内容,再断开连接...
 * 缺点: 很明显要建立多次连接,效率太差.
 * 如果接收端窗口小的时候,会产生半包问题
 * @date 2021-12-06 14:10
 **/
@Slf4j
public class FirstSolutionServer {
    public static void main(String[] args) {
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boss, worker);
            serverBootstrap.channel(NioServerSocketChannel.class);
            //netty应用层接收的ByteBuf默认大小为64,我们此时设置为16,当发送超过16个字节时,就会发生半包现象
            serverBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(16, 16, 16));
            ChannelFuture future = serverBootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                    nioSocketChannel.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                }
            }).bind(8080).sync();
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("server error", e);
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }

}
